<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Calculator</title>

</head>

<body>
	<h1>PHP Calculator</h1>
	<p>Please type an expression in the following box:</p>

	<form name="calculator" action="calculator.php" method="POST">
		<input type="text" name="expression" />
    	<input type="submit" name="submit" value="Calculate" />
	</form>
	
<?php

	
	if(!empty($_POST['expression']) ){
	
	$exp = $_POST['expression'];
	//Remove spaces

	$exp = preg_replace('/\s+/', '', $exp);

	$number = '-?[0-9]*\.?[0-9]+';
	$operation = '[\+\*\/]';
	
	//   ^((-)?[0-9]*\.?[0-9]+)(([\+\*\/]?-?[0-9]*\.?[0-9]+)*)$	
	$regex = '/^((-)?[0-9]*\.?[0-9]+)(([\+\*\/]?-?[0-9]*\.?[0-9]+)*)$/';
	// '/^('.$number.')(('.$operation.'?'.$number.')*)$/';
	
	if(preg_match($regex, $exp)) {
		if(strpos($exp, "/0") > -1)
			echo $exp.' =';
		else {
			eval('$result='.$exp.';');
			echo $exp.' = '.$result;
		}
	} else {
		$result = false;
		echo "Invalid input expression ".$exp;
	}
	}
?>

</body>
</html>